package samsung.sds.system.security.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import samsung.sds.survey.surveyList.service.SurveyListService;
import samsung.sds.system.utils.CommonTools;
import samsung.sds.userManagement.model.UserEntity;
import samsung.sds.userManagement.service.UserManagementService;

@Controller
public class LoginController {
	
	@Autowired
	private UserManagementService userManagementServiceImpl;
	
	@Autowired
	private SurveyListService surveyListServiceImpl;
		
	private UserDetails userDetails;
	
	@RequestMapping("/login")
	public String loginPage(@RequestParam(value = "error", required = false) boolean error, ModelMap model){
			if(error){
				String errorValue = "You have entered an invalid username or password!";
				model.addAttribute("error", errorValue);
			}
			return "/common/login";
	}
	
	@RequestMapping("/index")
	public String indexPage(ModelMap model,HttpServletRequest request){
		 
			userDetails = (UserDetails) SecurityContextHolder.getContext()
				    .getAuthentication()
				    .getPrincipal();
			
			String username = CommonTools.getSessionUserName();
			
			if(!"".equals(username)){
				request.getSession().setAttribute("SESSION_USERNAME",username);			
				UserEntity user = new UserEntity();
				user.setUsername(username);
				user = userManagementServiceImpl.findUniqueByProperty(user);			
				if(user!=null){
					request.getSession().setAttribute("SESSION_USERNAME_CN",user.getCn_name());
				}
				String authorities = "";
				for(Object auth:userDetails.getAuthorities().toArray()){
					authorities+=auth.toString()+",";				
				}
				request.getSession().setAttribute("SESSION_AUTHORITY",authorities);
				//获取状态数据 
				int alreadyVotedCount  = surveyListServiceImpl.selectTF_F_SURVEY_USER02(username);//已投票
				int waitVotedCount   = surveyListServiceImpl.selectTF_F_SURVEY_USER01(username);//待投票总数
				int endVotedCount   = surveyListServiceImpl.selectTF_F_SURVEY_USER03(username);//结束
				int participated   = surveyListServiceImpl.selectTF_F_SURVEY_USER04(username);//参与
				
				model.addAttribute("alreadyVotedCount", alreadyVotedCount);
				model.addAttribute("waitVotedCount", waitVotedCount);
				model.addAttribute("endVotedCount", endVotedCount);
				model.addAttribute("participated", participated);
			}
		 
		return "/../../index";
		
	}
	
	
	@RequestMapping("/session")
	public String indexSessionPage(ModelMap model,HttpServletRequest request){
		return "/common/sessionTimeOut";
	}
		
}
